package controller

import (
	"github.com/labstack/echo"
	"github.com/sirupsen/logrus"
	"net/http"
	"src/config"
	"src/controller/param"
	"src/model"
	"src/util/context"
	"src/util/log"
)

var userLogger = log.GetLogger()

func writeuserLoggerLoggerLog(funcName, errMsg string, err error) {
	userLogger.WithFields(logrus.Fields{
		"package":  config.LogMessage,
		"file":     "user.go",
		"function": funcName,
		"err":      err,
	}).Warn(errMsg)
}

func ChangeUserMsg(c echo.Context) error {
	User := param.UserMsgChange{}
	err := c.Bind(&User)
	writeuserLoggerLoggerLog("ChangeUserMsg", "1", err)
	if err != nil {
		writeuserLoggerLoggerLog("ChangeUserMsg", config.ErrorMsgParamWrong, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}
	id := context.GetJWTUserOpenid(c)
	writeuserLoggerLoggerLog("ChangeUserMsg", "2", err)
	NewUser := model.User{
		Name:   User.Name,
		Gender: User.Gender,
		School: User.School,
		Grade:  User.Grade,
		Openid: id,
	}
	err = model.ChangeUserMsg(NewUser)
	writeuserLoggerLoggerLog("ChangeUserMsg", "3", err)
	if err != nil {
		writeuserLoggerLoggerLog("ChangeUserMsg", config.ErrorChangeUser, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorChangeUser)
	}
	writeuserLoggerLoggerLog("ChangeUserMsg", "4", err)
	return context.RetData(c, "")
}

func GetUserInfo(c echo.Context) error {
	user_id := param.Id{}
	err := c.Bind(&user_id)
	if err != nil {
		writeuserLoggerLoggerLog("GetUserInfo", config.ErrorMsgParamWrong, err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}
	id := context.GetJWTUserOpenid(c)
	resData := map[string]interface{}{}
	resData["Info"], err = model.GetUserInfo(id)
	if err != nil {
		writeuserLoggerLoggerLog("GetUserInfo", "err get userinfo", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, err.Error())
	}
	writeuserLoggerLoggerLog("GetUserInfo", "success", err)
	return context.RetData(c, resData)
}
